package UDP;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

//服务端
public class test1 {
    public static void main(String[] args) {
        DatagramSocket datagramSocket = null;
        try {
            //1.给定地址端口
            datagramSocket = new DatagramSocket(8080);
            //2.接收数据
            byte[] buffer = new byte[1024];//字节大小
            DatagramPacket Packet = new DatagramPacket(buffer,0,buffer.length);//创建包用来存放收到的包
            datagramSocket.receive(Packet);//阻塞接收
            //2.2打印包中的数据
            System.out.println(Packet.getAddress().getHostName());//获取是谁发送到
            System.out.println(new String(Packet.getData(),0,Packet.getLength()));//获取发送的内容


        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //3.关闭socket套接字
            if (datagramSocket!=null){
                datagramSocket.close();
            }
        }
    }
}
